import base64
import io
import json
import numpy as np
import PIL.Image

IMG_EXTENSIONS = ['.jpg', '.jpeg', '.png']
DICOM_EXTENSIONS = ['dcm']


def has_file_allowed_extension(filename, extensions):
    """Checks if a file is an allowed extension.

    Args:
        filename (string): path to a file
        extensions (iterable of strings): extensions to consider (lowercase)

    Returns:
        bool: True if the filename ends with one of given extensions
    """
    filename_lower = filename.lower()
    return any(filename_lower.endswith(ext) for ext in extensions)

def img_b64_to_arr(img_b64):
    f = io.BytesIO()
    f.write(base64.b64decode(img_b64))
    img_arr = np.array(PIL.Image.open(f))
    return img_arr


def img_arr_to_b64(img_arr):
    img_pil = PIL.Image.fromarray(img_arr)
    f = io.BytesIO()
    img_pil.save(f, format='PNG')
    img_bin = f.getvalue()
    img_b64 = base64.encodestring(img_bin)
    return img_b64


def img_arr_to_b64_json(img_arr):
    img_pil = PIL.Image.fromarray(img_arr)
    f = io.BytesIO()
    img_pil.save(f, format='PNG')
    img_bin = f.getvalue()
    img_b64 =  base64.b64encode(img_bin).decode('utf-8')
    with open('tmp.json', 'w') as f:
        json.dump(img_b64, f, ensure_ascii=False, indent=2)

def img_arr_to_b64_json_v2(img_arr):
    img_b64 =  base64.b64encode(img_arr.data).decode('utf-8')
    with open('tmp.json', 'w') as f:
        json.dump(img_b64, f, ensure_ascii=False, indent=2)

def json_img_b64_to_arr_v2():
    with open('tmp.json', 'r') as f:
        img_b64 = json.load(f)

    f = io.BytesIO()
    f.write(base64.b64decode(img_b64))
    img_arr = np.array(PIL.Image.open(f))
    return img_arr


def read(filename, default=None):
    try:
        with open(filename, 'rb') as f:
            return f.read()
    except Exception:
        return default

def file_to_b64_json(filename):
    imageData = read(filename, None)
    img_b64 = base64.b64encode(imageData).decode('utf-8')
    with open('tmp.json', 'w') as f:
        json.dump(img_b64, f, ensure_ascii=False, indent=2)

def json_img_b64_to_arr():
    with open('tmp.json', 'r') as f:
        img_b64 = json.load(f)

    f = io.BytesIO()
    f.write(base64.b64decode(img_b64))
    img_arr = np.array(PIL.Image.open(f))
    return img_arr

def is_image_file(filename):
    """Checks if a file is an allowed image extension.

    Args:
        filename (string): path to a file

    Returns:
        bool: True if the filename ends with a known image extension
    """
    return has_file_allowed_extension(filename, IMG_EXTENSIONS)

def is_dcm_file(filename):
    """Checks if a file is an allowed image extension.

        Args:
            filename (string): path to a file

        Returns:
            bool: True if the filename ends with a known image extension
        """
    return has_file_allowed_extension(filename, DICOM_EXTENSIONS)


if __name__ == "__main__":
    filename = '/home/blake/medical/data/63225626_img.png'

